from django.shortcuts import render, HttpResponse, redirect

# Create your views here.
def login(request):
	if request.method == "GET":
		print(request.session.get('is_login'))
		if request.session.get('is_login'):

			return redirect('/index/')
		return render(request, 'login.html')
	elif request.method == "POST":
		user = request.POST.get('user')
		pwd = request.POST.get('pwd')
		if user == 'root' and pwd == '123':
			# session 设置值
			request.session['username'] = user
			request.session['is_login'] = True
			if request.POST.get('rmb') == "1":
				request.session.set_expiry(10)
			return redirect('/index/')
		else:
			return render(request, 'login.html')

from django.views.decorators.csrf import csrf_exempt,csrf_protect

@csrf_protect
def index(request):
	# session中获取值
	if request.session.get('is_login'):
		return render(request, 'index.html')
		# return HttpResponse(request.session['username'])
	else:
		# return HttpResponse('invalid')
		return redirect('/login/')

def logout(request):
	request.session.clear()
	# request.session.delete("")
	return redirect('/login/')

def test(request):
	print('this is test')
	return HttpResponse('hehe')

from django.views.decorators.cache import cache_page
# @cache_page(5) # time to invalidate
def cache(request):
	import time
	ctime = time.time()
	return render(request, 'cache.html', {'ctime':ctime})

def signal(request):
	from app01 import models
	obj = models.UserInfo(user='root')
	print('end')
	obj.save()
	return HttpResponse('ok')

from django import forms
class FM(forms.Form):
	user = forms.CharField(error_messages={'required':'用户名不能为空'})
	pwd = forms.CharField(error_messages={'required':'密码不能为空'})
	email = forms.EmailField(error_messages={'required':'邮箱不能为空','invalid':'无效邮箱'})

def fm(request):
	if request.method == "GET":
		return render(request,'fm.html')
	if request.method == "POST":
		obj = FM(request.POST)
		rt = obj.is_valid()
		if rt:
			print(obj.cleaned_data)
		else:
			print(obj.errors)
			# return HttpResponse(obj.errors)
		return render(request,'fm.html')